package CH03分治回溯;

import java.util.ArrayList;
import java.util.List;

public class LC47 {
    List<List<Integer>> lists = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        permutation(nums, 0);
        return lists;
    }
    private void permutation(int[] nums, int k) {
        if (k == nums.length) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }
            lists.add(list);
        }
        for (int i = k; i < nums.length; i++) {
            if (check(nums, i, k)) {
                swap(nums, i, k);
                permutation(nums, k + 1);
                swap(nums, i, k);
            }
        }
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    private boolean check(int[] nums, int i, int k) {
        for (int j = k; j < i; j++) {
            if (nums[j] == nums[i]) {
                return false;
            }
        }
        return true;
    }
}